package com.lj.framework.common.codecs;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {

    public static String encodeMd5(String str) throws Exception{
        MessageDigest mdInst;
        try{
            mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(str.getBytes("UTF-8"));
            return toHex(mdInst.digest());
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
            throw new Exception("不支持MD5");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            throw new Exception("不支持MD5");
        }
    }

    private static String toHex(byte buffer[]){
        StringBuffer sb = new StringBuffer(buffer.length*2);
        for(int i=0; i < buffer.length; i++){
            sb.append(Character.forDigit((buffer[i]&240) >> 4, 16));
            sb.append(Character.forDigit((buffer[i]&15) , 16));
        }
        return sb.toString();
    }
}
